﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;

namespace Portal.CMS
{
    public class Html : Portal.Interface.WebPart
    {
        public override string WebPartId
        {
            get
            {
                return "Html";
            }
        }

      
        public override bool IsMainWebPart
        {
            get
            {
                return true;
            }
        }

        public override string Title
        {
            get
            {
                return ResourceBLL.GetText(WebPartId,"Title","Quản lý bài viết");
            }
        }

        public override string Description
        {
            get
            {
                return ResourceBLL.GetText(WebPartId,"Description","");
            }
        }


        public override Portal.Interface.WebPartInt[] SubWebParts
        {
            get
            {
                Portal.Interface.WebPartInt[] SubWebParts = new Portal.Interface.WebPartInt[]{
                    new AddHtml(),new UpdateHtml(),new HtmlPreview()
                };
                return SubWebParts;
            }
        }


        public override string RenderWebPart(LoadParamCls loadParamCls)
        {
            try
            {
                AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.CMS.Html));
                Environments.CheckWebPartAllow(WebPartId, true);
                Environments.CheckSessionTimeOut(true);

                string ActiveSite = Portal.Environment.Environments.GetActiveSite();
                string RetHtml =
                    Portal.Environment.WebPartUtilities.AttachJavascript("Portal.CMS", "Html.js") +
                    "<div class=cssHtmlMain>" +
                    "   <div id=divHtmlContent>" + GetHtml(ActiveSite, "", 0) + "</div>" +
                    "</div>";
                return RetHtml;
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

      
        [AjaxPro.AjaxMethod]
        public string GetHtml(string belongSite,string WorkFlowStatus, int PageIndex)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);


                string SelectSite =ResourceBLL.GetText(WebPartId,"SelectSite","Chọn site")+": "+
                         "<select id=drpSelectSiteForHtml onchange=javascript:RunFilter();>";
                string[] Sites = Environments.GetSites();
                for (int iIndex = 0; iIndex < Sites.Length; iIndex++)
                {
                    if (Sites[iIndex].ToLower().Equals(belongSite))
                    {
                        SelectSite += "<option selected value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
                    }
                    else
                    {
                        SelectSite += "<option value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
                    }
                }
                SelectSite += "</select>";

                DataTable dtWorkFlowStatus = new HtmlBLL().ReadingWorkflowStatus(belongSite);
                string SelectWorkFlowStatusText = ResourceBLL.GetText(WebPartId, "WorkflowStatusText", "Trạng thái") + ": <select id=divSelectWorkflowStatus>";
                for (int iIndex = 0; iIndex < dtWorkFlowStatus.Rows.Count; iIndex++)
                {
                    string tWorkflowStatus = (string)dtWorkFlowStatus.Rows[iIndex]["WorkflowStatus"];
                    if (WorkFlowStatus.Trim().Length == 0 && iIndex==0)
                    {
                        WorkFlowStatus = tWorkflowStatus;
                    }
                    
                    if (WorkFlowStatus.Equals(tWorkflowStatus))
                    {
                        SelectWorkFlowStatusText += "<option selected value=\"" + tWorkflowStatus + "\">" + tWorkflowStatus + "</option>";
                    }
                    else
                    {
                        SelectWorkFlowStatusText += "<option value=\"" + tWorkflowStatus + "\">" + tWorkflowStatus + "</option>";
                    }
                }
                SelectWorkFlowStatusText += "</select>";

                
                string RetHtml = "";
                string ActiveLanguage = Environments.ActiveLanguage;
                DataTable dtHtml = new HtmlBLL().Reading(belongSite,ActiveLanguage, WorkFlowStatus);
                int ItemPerPage = 20;
                int MaxPage = dtHtml.Rows.Count / ItemPerPage;
                if (dtHtml.Rows.Count % ItemPerPage != 0) MaxPage++;
                int StartIndex = PageIndex * ItemPerPage;
                int EndIndex = StartIndex + ItemPerPage;
                if (EndIndex > dtHtml.Rows.Count) EndIndex = dtHtml.Rows.Count;

                string SelectPageText = ResourceBLL.GetText(WebPartId,"PageText","Trang") + ": <select id=divSelectPage>";
                for (int iIndex = 0; iIndex < MaxPage; iIndex++)
                {
                    if (PageIndex == iIndex)
                    {
                        SelectPageText += "<option selected>" + (iIndex + 1) + "</option>";
                    }
                    else
                    {
                        SelectPageText += "<option>" + (iIndex + 1) + "</option>";
                    }
                }
                SelectPageText += "</select>";


                RetHtml +=
                    SelectSite + SelectPageText + SelectWorkFlowStatusText + "<input type=button onclick=javascript:RunFilter(); value=\"" + ResourceBLL.GetText(WebPartId, "ReadingText", "Đọc dữ liệu") + "\"><input type=button value=\"" + ResourceBLL.GetText(WebPartId, "AddText", "Thêm mới") + "\" onclick=javascript:ClientAddHtml();>" +
                    "   <div id=divProcessing></div>";

                if (dtHtml.Rows.Count == 0)
                {
                    RetHtml += "<div class=\"cssNoData\">" + ResourceBLL.GetText(WebPartId, "NoData", "Chưa có dữ liệu nào trong chuyên mục này!") + "</div>";
                }
                else
                {
                    RetHtml += "<table class=cssHtmlContent>" +
                               "  <tr>" +
                               "      <th class=cssCol0>#</th>" +
                               "      <th class=cssCol0>" + ResourceBLL.GetText(WebPartId, "AliasText", "Alias") + "</th>" +
                               "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "SubjectText", "Tiêu đề") + "</th>" +
                               "      <th class=cssCol2>" + ResourceBLL.GetText(WebPartId, "EntryDate", "Ngày nhập") + "</th>" +
                               "      <th class=cssCol3></th>" +
                               "      <th class=cssCol4></th>" +
                               "      <th class=cssCol5></th>" +
                               "      <th class=cssCol6></th>" +
                               "      <th class=cssCol7></th>" +
                               " </tr>";
                    for (int iIndex = StartIndex; iIndex < EndIndex; iIndex++)
                    {
                        string HtmlId = (string)dtHtml.Rows[iIndex]["HtmlId"];
                        string SubjectText = "";
                        try
                        {
                            SubjectText = (string)dtHtml.Rows[iIndex]["Subject"];
                        }
                        catch (Exception ex)
                        {
                            SubjectText = "(N/A)";
                            ex.Source = "";
                        }
                        string Alias = "";
                        try
                        {
                            Alias = (string)dtHtml.Rows[iIndex]["Alias"];
                        }
                        catch
                        {
                        }
                        DateTime EntryDate = (DateTime)dtHtml.Rows[iIndex]["EntryDate"];
                        string tWorkFlowStatus = (string)dtHtml.Rows[iIndex]["WorkFlowStatus"];
                        int IsPublishing = (int)dtHtml.Rows[iIndex]["IsPublishing"];
                        string PublishingHtml = "<a href=\"javascript:ClientPublishingHtml('" + HtmlId + "');\">" + ResourceBLL.GetText(WebPartId, "Publishing", "(Xuất bản)") + "</a>";
                        if (IsPublishing == 1)
                        {
                            PublishingHtml = "<a href=\"javascript:ClientUnPublishingHtml('" + HtmlId + "');\">" + ResourceBLL.GetText(WebPartId, "UnPublishing", "(Ngừng)") + "</a>";
                        }

                        string LinkUrl = Environments.GetStaticHtmlUrl(belongSite, Alias, SubjectText);
                        RetHtml +=
                               "  <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                               "      <td>" + (iIndex + 1) + "</td>" +
                               "      <td>" + Alias + "</td>" +
                               "      <td>" + SubjectText + "</td>" +
                               "      <td>" + EntryDate.ToString("dd/MM/yyyy") + "</td>" +
                               "      <td><a href=\"javascript:ShowUpdateHtmlForm('" + HtmlId + "');\">" + ResourceBLL.GetText(WebPartId, "UpdateText", "Cập nhật") + "</a></td>" +
                               "      <td><a href=\"javascript:ClientDeleteHtml('" + HtmlId + "');\">" + ResourceBLL.GetText(WebPartId, "DeleteText", "Xóa") + "</a></td>" +
                               "      <td>" + tWorkFlowStatus + "</td>" +
                               "      <td>" + PublishingHtml + "</td>" +
                               "      <td><a href=\"javascript:ClientSyncHtml('" + HtmlId + "');\">" + ResourceBLL.GetText(WebPartId, "Sync", "Sync") + "</a></td>" +
                               " </tr>";
                        if (Alias.Trim().Length > 0)
                        {
                            RetHtml +=
                               "  <tr>" +
                               "        <td colspan=8><a href=\"" + LinkUrl + "\">" + LinkUrl + "</a></td>" +
                               "  </tr>";
                        }
                    }
                    RetHtml += "</table>";
                }
                return RetHtml;
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetAddNewUrl(string belongSite)
        {
            return Portal.Environment.Screen.BuildDialogUrl(new ParamCls[]{
                new ParamCls("WebPartId",new AddHtml().WebPartId),
                new ParamCls("belongSite",belongSite)
            });
        }

        [AjaxPro.AjaxMethod]
        public string GetConfirmMsg()
        {
            return ResourceBLL.GetText(WebPartId,"ConfirmDeleteMsg","Bạn đã chắc chắn xóa chưa?");
        }

        [AjaxPro.AjaxMethod]
        public string GetConfirmPublishingMsg()
        {
            return ResourceBLL.GetText(WebPartId, "ConfirmPublishingMsg", "Bạn đã chắc chắn XUẤT BẢN chưa?");
        }

        [AjaxPro.AjaxMethod]
        public string GetConfirmUnPublishingMsg()
        {
            return ResourceBLL.GetText(WebPartId, "ConfirmUnPublishingMsg", "Bạn đã chắc chắn NGỪNG xuất bản chưa?");
        }

        [AjaxPro.AjaxMethod]
        public string GetConfirmSyncAllMsg()
        {
            return ResourceBLL.GetText(WebPartId, "ConfirmSyncAllMsg", "Bạn đã chắc chắn update lại dữ liệu tin tức trên máy chủ từ máy local chưa?");
        }


        [AjaxPro.AjaxMethod]
        public string GetDeleteOkMsg()
        {
            return ResourceBLL.GetText(WebPartId,"DeleteOk","Xóa thành công!");
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideDeleteHtml(string HtmlId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                
                SqlTransaction sqlTransaction = Environment.Environments.CreateTransaction();
                try
                {
                    new HtmlBLL().DeleteHtml(sqlTransaction, HtmlId);
                    sqlTransaction.Commit();
                }
                catch (Exception ex)
                {
                    sqlTransaction.Rollback();
                    throw (ex);
                }
                return ResourceBLL.GetText(WebPartId,"DeleteOk","Xóa bài viết thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetUpdateHtmlUrl(string HtmlId)
        {
            return Screen.BuildDialogUrl(new ParamCls[]{
                new ParamCls("WebPartId",new UpdateHtml().WebPartId),
                new ParamCls("HtmlId",HtmlId)
            });
        }

        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                string Url = Environment.Environments.GetActiveThemeUrl() + "/Global/Loading.gif";
                return "<img src=\"" + Url + "\"><a class=cssProcessing>" + ResourceBLL.GetText(WebPartId, "ProcessingText", "Đang đọc dữ liệu...") + "</a>";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string ServerSidePublishing(string HtmlId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new HtmlBLL().PublishingHtml(null, HtmlId);
                return ResourceBLL.GetText(WebPartId,"PublishingOk","Xuất bản thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideUnPublishing(string HtmlId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new HtmlBLL().UnPublishingHtml(null, HtmlId);
                return ResourceBLL.GetText(WebPartId, "UnPublishingOk", "Ngừng xuất bản thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideSyncToServer(string HtmlId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new HtmlBLL().SyncWithServer(HtmlId);
                return GetText("SyncOk", "Sync với máy chủ web thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

    }
}
